package com.tiancheng.onecode.aop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.tiancheng.onecode.feign.TCFeignClient;
import com.tiancheng.onecode.model.dto.PayMerchantDTO;
import com.tiancheng.onecode.model.dto.PayPlatformDTO;
import com.tiancheng.onecode.model.response.Result;
import com.tiancheng.onecode.service.IMerchantService;
import com.tiancheng.onecode.service.IPlatformService;
import com.tiancheng.onecode.utils.MerchantContext;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;

/**
 * @author jiangjun
 * @description 天成登录认证拦截
 * @date 2024/12/10 10:51
 */
@Component
@Slf4j
public class TCAuthRequestInterceptor implements HandlerInterceptor {

    @Lazy
    @Autowired
    private TCFeignClient tcFeignClient;
    @Autowired
    private Environment environment;
    @Resource
    private IMerchantService merchantService;
    @Resource
    private IPlatformService platformService;

    public static final String[] IGNORED_URLS = new String[]{"/notify/payCallback"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String MerchantCode = request.getHeader("MerchantCode");
        if (StringUtils.isNotBlank(MerchantCode)) {
            PayMerchantDTO payMerchantDTO = merchantService.queryPayMerchantByCode(MerchantCode);
            MerchantContext.setMerchant(payMerchantDTO);
        }

        String platformCode = request.getHeader("PlatformCode");
        if (StringUtils.isBlank(platformCode)) {
            platformCode = "default";
        }
        PayPlatformDTO payPlatformDTO = platformService.getDefaultOne(platformCode);
        MerchantContext.setPlatform(payPlatformDTO);
        if (getActiveProfile().equals("dev")) {
            return true;
        }
        final String requestURI = request.getRequestURI();
        // 获取请求头信息
        String token = request.getHeader("X-Token");
        for (String ignoredUrl : IGNORED_URLS) {
            if (requestURI.startsWith(ignoredUrl)) {
                log.info("不授权的请求地址：{}", requestURI);
                return true;
            }
        }

        String requestSource = "";
        if (requestURI.startsWith("/api/c/")) {
            // 移动端-消费者端
            requestSource = "移动端-消费者C端";
        } else if (requestURI.startsWith("/api/b/")) {
            // 移动端-商家管理端
            requestSource = "移动端-商家管理B端";
        } else if (requestURI.startsWith("/admin/platform/")) {
            requestSource = "PC端-平台管理端";
        } else {
            requestSource = "PC端-商户管理管理端";
        }
        long startTime = System.currentTimeMillis();
        log.info("登录认证校验--->> 请求来源【{}】,url:{},token:{}", requestSource, requestURI, token);
        String checkLogin1 = tcFeignClient.CheckLogin1(new HashMap<>(), token);
        log.info("checkLogin1 result: {}", checkLogin1);
        long endTime = System.currentTimeMillis();
        log.info("登录认证校验完成，耗时：【{} ms】",endTime - startTime);
        JSONObject jsonObject = JSON.parseObject(checkLogin1);
        if (jsonObject.getBoolean("successFlag")) {
            return true;
        } else {
            // 登录失败，返回自定义的 JSON 格式数据
            response.setStatus(HttpServletResponse.SC_OK); // 设置 HTTP 状态码为 401 未授权
            response.setContentType("application/json;charset=UTF-8"); // 设置响应的内容类型为 JSON 格式
            // 将 JSON 数据写入响应
            response.getWriter().write(JSON.toJSONString(Result.fail(401, "暂未登录或token已经过期!")));
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
        // 进行后处理（例如：记录日志等）
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后执行清理操作（例如：关闭资源等）
        MerchantContext.clear();
    }

    /**
     * 获取当前环境
     *
     * @return
     */
    private String getActiveProfile() {
        String[] activeProfiles = environment.getActiveProfiles(); // 获取激活的配置文件
        return activeProfiles.length > 0 ? activeProfiles[0] : "default";
    }
}
